package com.woniuxy.controller;


import com.woniuxy.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class NotificationHandler extends TextWebSocketHandler {
    @Autowired
    private MessageService messageService;

    // 存储用户ID与WebSocket会话的映射
    private static final Map<String, WebSocketSession> notificationSessions = new ConcurrentHashMap<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // 从URL路径中提取userId
        String path = session.getUri().getPath();
        String userId = path.substring(path.lastIndexOf('/') + 1);

        if (userId != null && !userId.isEmpty()) {
            notificationSessions.put(userId, session);
            System.out.println("通知连接建立: " + userId + ", 当前在线: " + notificationSessions.size());
        }
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) {
        // 可以处理心跳消息等
        System.out.println("收到通知消息: " + message.getPayload());
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        // 移除关闭的会话
        notificationSessions.values().removeIf(s -> s.getId().equals(session.getId()));
        System.out.println("通知连接关闭, 剩余在线: " + notificationSessions.size());
    }
    private  int getUnreadCount(String userId, String senderId) {
        // 获取未读消息计数
        Integer unreadCount = messageService.findUnreadCount(userId, senderId);
        return unreadCount != null ? unreadCount : 0;

    }

    /**
     * 发送新消息通知
     * @param userId 接收通知的用户ID
     * @param senderId 消息发送者ID
     */
    public  void sendNewMessageNotification(
            String userId, String senderId, String message, LocalDateTime timestamp,Integer unreadCount ) {
        WebSocketSession session = notificationSessions.get(userId);
        if (session != null && session.isOpen()) {
            try {
                // 格式化时间戳
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                String formattedTime = timestamp.format(formatter);

                // 构建通知消息（包含最后一条消息内容）
                String notification = String.format(
                        "{\"type\":\"NEW_MESSAGE\",\"senderId\":\"%s\",\"content\":\"%s\",\"timestamp\":\"%s\",\"unreadCount\":%d}",
                        senderId,
                        message,
                        formattedTime,
                        unreadCount
                );
                session.sendMessage(new TextMessage(notification));
                System.out.println("发送新消息通知给用户: " + userId + ", 发送者: " + senderId);
            } catch (IOException e) {
                System.err.println("发送通知失败: " + e.getMessage());
            }
        } else {
            System.out.println("用户 " + userId + " 的通知会话不存在或未打开");
        }
    }
}
